import {
  exportDataApi,
  exportPayableShipmentExcelApi,
  getListApi,
  getPageStaticApi,
  preAcceptedPagStateApi,
  revokePayableStatementApi,
  statisticsDataApi,
  withdrawBillApi
} from "@/api/financialManagement/payableManagement/index";
// import CommonHook from "@/hook/commonHook";
import { message, Modal } from "ant-design-vue";
import { Ref, computed, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
export default function OperationHook(state: {
  searchForm: StatementPayable.SearchForm;
  tableData: Ref<StatementPayable.ListRows[]>;
  tableRef: Ref<any>;
  dialogOpts: Base.DialogOpts;
  drawerOpts: Base.DrawerOpts;
  loading: Ref<boolean>;
  activeKey: Ref<string>;
  pageStat: Ref<Base.GeneraDataType>;
  preAcceptedCount: Ref<number>;
}) {
  const { searchForm, tableData, drawerOpts, loading, tableRef, dialogOpts, activeKey, pageStat, preAcceptedCount } = state;
  const selectRows = computed<Array<StatementPayable.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  // const { downloadFileByBlob } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams(),
      statusList: [Number(activeKey.value)]
    };
    loading.value = true;
    tableData.value = [];
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.beforePageNum = searchForm.pageNum;
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const { agentIdList, statementType, companyIdList, waybillNum, payableStatementNumber, beforePageNum, pageNum, pageSize } = searchForm;
    const params: any = {
      agentIdList,
      statementType,
      companyIdList,
      beforePageNum,
      pageNum,
      pageSize
    };
    if (waybillNum)
      params.waybillNum = waybillNum
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (payableStatementNumber)
      params.payableStatementNumber = payableStatementNumber
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }
    return params;
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi({ ...params }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          1: data[1],
          2: data[2]
        });
        // activeKey.value = String(getNoZeroKey(pageStat.value, ["1", "2"]));
      }
    });
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
    getPreAcceptedPageCount();
  };
  const changeTabHandle = () => {
    getData();
  };
  const getPreAcceptedPageCount = () => {
    return preAcceptedPagStateApi().then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        preAcceptedCount.value = data;
      }
    });
  };
  // 详情
  const showDetailsHandle = (row: StatementPayable.ListRows) => {
    drawerOpts.title = `详情`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 导入对账单
  const importStatementHandle = () => {
    dialogOpts.title = `导入对账单`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ImportStatement";
    dialogOpts.visible = true;
  };
  // 导入 加收单
  const importAddFeeHandle = () => {
    dialogOpts.title = `导入加收单`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "ImportStatement";
    dialogOpts.visible = true;
  };
  // 导出
  const downloadDataHandle = () => {
    let params: any;

    if (selectRows.value.length) {
      params = {
        idList: selectRows.value.map((t: any) => t.id),
        statusList: [activeKey.value]
      };
    } else {
      params = {
        ...getParams(),
        statusList: [activeKey.value]
      };
    }

    return exportDataApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };
  // 撤销账单
  const reverseBillHandle = (row: StatementPayable.ListRows) => {
    Modal.confirm({
      title: "是否撤销当前账单?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        revokePayableStatementApi(row.id).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("撤销成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 待接收账单
  const showPreAcceptedBillHandle = () => {
    drawerOpts.title = `待接收账单`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "PreAcceptedBill";
    drawerOpts.visible = true;
  };
  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams(),
      statusList: [Number(activeKey.value)]
    };
    if (selectRows.value.length) params.idList = selectRows.value.map((t: StatementPayable.ListRows) => t.id);
    return statisticsDataApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };
  // 查看统计
  const showStatictisHandle = () => {
    dialogOpts.title = "查看统计";
    dialogOpts.width = "900px";
    dialogOpts.component = "DataStatistics";
    dialogOpts.visible = true;
  };
  //导出对账
  const exportStatementHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    loading.value = true;
    return exportPayableShipmentExcelApi(selectRows.value.map((t: any) => t.id))
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("创建任务成功，请前往导出中心下载！");
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  //应付对账单 - 撤销已生成的账单
  const withdrawBillHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    loading.value = true;
    return withdrawBillApi(selectRows.value.map((t: any) => t.id))
      .then(({ code }: any) => {
        if (code === 200) {
          message.success("撤销成功!");
          searchHandle();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  return {
    searchHandle,
    getData,
    showDetailsHandle,
    importStatementHandle,
    importAddFeeHandle,
    changeTabHandle,
    downloadDataHandle,
    reverseBillHandle,
    selectRows,
    showPreAcceptedBillHandle,
    getStatisticsDataFn,
    showStatictisHandle,
    exportStatementHandle,
    withdrawBillHandle
  };
}
